package cqie.frame.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import cqie.frame.entity.Dept;
import cqie.frame.entity.Emp;
import cqie.frame.entity.RoleMenu;
import cqie.frame.entity.SysMenu;
import cqie.frame.entity.po.DeptPo;
import cqie.frame.entity.po.SysMenuPo;
import cqie.frame.entity.vo.DeptTreeData;
import cqie.frame.entity.vo.SysMenuTreeData;
import cqie.frame.response.CodeMsg;
import cqie.frame.response.ResultJson;
import cqie.frame.service.IDeptService;
import cqie.frame.service.IEmpService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (Dept)表控制层
 *
 * @author makejava
 * @since 2021-09-27 08:47:20
 */
@Api
@RestController
@RequestMapping("/dept")
public class DeptController extends ApiController {
    /**
     * 服务对象
     */
    @Resource
    private IDeptService ideptService;
    @Resource
    private IEmpService iEmpService;


    //新增部门
    @ApiOperation(value = "新增部门", notes = "新增部门，同时更新部门表。", response = Dept.class)
    @PostMapping(value = "/addDept")
    public ResultJson addMenu(Dept dept) {
        try {
            //构造mo
            Dept dept1 = new Dept();
            //复制po的属性到Drpt,第三个参数可选，为忽略某些属性
            BeanUtils.copyProperties(dept, dept1);
            //插入部门表后回显插入部门的主键id
            ideptService.save(dept1);
            dept.setId(dept1.getId());
            //返回部门
            return ResultJson.success(dept);
        } catch (Exception e) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    //修改部门
    @ApiOperation(value = "修改部门", notes = "修改部门，同时更新部门表。")
    @PostMapping(value = "/updateDept")
    public ResultJson updateDept(@RequestBody Dept po) {
        try {
            Dept dept = new Dept();
            //复制po的属性到dept,第三个参数可选，为忽略某些属性
            BeanUtils.copyProperties(po, dept);
            if (dept.getId() == null) {
                ideptService.save(dept);
                return ResultJson.success("新增成功");
            }
            if (po.getParentId() == null) {
                dept.setParentId(null);
            }
            ideptService.updateById(dept);
            return ResultJson.success("修改成功");
        } catch (Exception e) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    //删除部门
    @ApiOperation(value = "删除单个部门", notes = "删除部门。")
    @GetMapping(value = "/deleteDept")
    public ResultJson deleteDept(long id) {
        try {
            //删除部门前先判断是否有员工属于该部门，若有员工属于该部门，提示不能删除
            QueryWrapper<Emp> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("deptId", id);
            List<Emp> empList = iEmpService.list(queryWrapper);
            //如果有员工属于该部门，提示不能删除
            if (empList.size() > 0) {
                return ResultJson.error(CodeMsg.EMP_ERROR);
            } else {
                ideptService.removeById(id);
                return ResultJson.success("删除成功");
            }
        } catch (Exception e) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    //批量删除部门
    @ApiOperation(value = "删除选中部门", notes = "删除部门，同时更新角色菜单表。")
    @PostMapping(value = "/deleteCheckMenu")
    public ResultJson deleteCheckMenu(@RequestBody Long[] menuIdList) {
        //删除部门前先判断是否有员工属于该部门，若有员工属于该部门，提示不能删除
        try {
            for (int i = 0; i < menuIdList.length; i++) {
                //选择器，只有RoleMenu的menuid等同于要删除菜单的id，才执行删除角色菜单表
                QueryWrapper<RoleMenu> qw = new QueryWrapper<>();
                qw.eq("menuId", menuIdList[i]);
            }
            for (int i = 0; i < menuIdList.length; i++) {
            }
            return ResultJson.success("删除成功");
        } catch (Exception e) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }


    //根据部门ID进入部门的详细页面
    @ApiOperation(value = "部门详情")
    @GetMapping(value = "selectDeptById")
    public ResultJson selectDeptById(long id) {
        try {
            //部门po类
            DeptPo po = new DeptPo();
            //1.部门信息
            //先根据部门id查到部门
            Dept dept = ideptService.getById(id);
            //复制dept的属性到po,第三个参数可选，为忽略某些属性
            BeanUtils.copyProperties(dept, po);
            if (dept.getParentId() != null) {
                QueryWrapper<Dept> queryWrapper = new QueryWrapper();
                queryWrapper.eq("id", dept.getParentId());
                Dept dept1 = ideptService.getOne(queryWrapper);
                po.setParentName(dept1.getName());
            }
            return ResultJson.success(po);
        } catch (Exception e) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }


    //查询部门的树表
    @ApiOperation(value = "部门树表", notes = "构造Element——UI需要的树形结构")
    @GetMapping(value = "/ListTreeData")
    public ResultJson ListTreeData() {
        try {
            List<DeptTreeData> ret = new ArrayList<>();
            List<Dept> all = ideptService.list(null);
            List<Dept> first = all.stream()
                    .filter(x -> x.getParentId() == null)
                    .sorted(Comparator.comparing(Dept::getSortCode))
                    .collect(Collectors.toList());
            for (Dept mo : first) {
                // generateTreeData(mo,ret,all);
                ret.add(generateTreeData(mo, all));
            }
            return ResultJson.success(ret);
        } catch (Exception e) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    /**
     * 递归方法--SysMenu-->SysMenuTreeData
     */
    private DeptTreeData generateTreeData(Dept mo, List<Dept> all) {
        DeptTreeData node = new DeptTreeData();
        BeanUtils.copyProperties(mo, node);

        List<Dept> children = all.stream()
                .filter(x -> x.getParentId() != null && x.getParentId().equals(mo.getId()))
                .collect(Collectors.toList());
        List<DeptTreeData> subNodeList = new ArrayList<>();
        for (Dept child : children) {
            subNodeList.add(generateTreeData(child, all));
        }
        node.setChildren(subNodeList);
        return node;
    }


    //修改部门时，不能选自自己和子节点作为父级部门树表
    @ApiOperation(value = "部门树表2", notes = "修改部门时，不能选自自己和子节点作为父级部门树表")
    @GetMapping(value = "/ListTreeData2")
    public ResultJson ListTreeData2(long id) {
        try {
            List<DeptTreeData> ret = new ArrayList<>();
            List<Dept> all = ideptService.list(null);
            List<Dept> first = all.stream()
                    .filter(x -> x.getParentId() == null && x.getId() != id)
                    .sorted(Comparator.comparing(Dept::getSortCode))
                    .collect(Collectors.toList());
            for (Dept mo : first) {
                // generateTreeData(mo,ret,all);
                ret.add(generateTreeData2(mo, all, id));
            }
            return ResultJson.success(ret);
        } catch (Exception e) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    /**
     * 递归方法--SysMenu-->SysMenuTreeData
     */
    private DeptTreeData generateTreeData2(Dept mo, List<Dept> all, long id) {
        DeptTreeData node = new DeptTreeData();
        BeanUtils.copyProperties(mo, node);

        List<Dept> children = all.stream()
                .filter(x -> x.getParentId() != null && x.getParentId().equals(mo.getId())
                        && x.getId() != id)
                .collect(Collectors.toList());
        List<DeptTreeData> subNodeList = new ArrayList<>();
        for (Dept child : children) {
            subNodeList.add(generateTreeData2(child, all, id));
        }
        node.setChildren(subNodeList);
        return node;
    }

}

